package top.fwpsl.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @auther: 风戏fw
 * @date: 2020/11/25
 */
@Component
public class RedisSubscriber extends MessageListenerAdapter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.err.println("通道----->" + stringRedisTemplate.getKeySerializer().deserialize(message.getChannel()));
        System.err.println("消息----->" + stringRedisTemplate.getValueSerializer().deserialize(message.getBody()));
    }

    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer(MessageListenerAdapter listenerAdapter,
                                                                JedisConnectionFactory jedisConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(jedisConnectionFactory);
        container.addMessageListener(listenerAdapter, Arrays.asList(new PatternTopic
                ("channel-fw-redistemplate")));
        return container;
    }
}
